<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>due client ts example</title>
</head>

<body>

</body>
<script type="module">
    import { Client, Packer } from '../dist/index.esm.js';

    // 请求数据包
    const buffer = (new TextEncoder).encode(JSON.stringify({
        message: 'hello server'
    }));

    // 创建客户端
    const client = new Client({
        url: 'ws://127.0.0.1:3553',
        heartbeat: 10000,
        packer: new Packer({
            byteOrder: 'big',
            seqBytes: 0,
            routeBytes: 4,
            bufferBytes: 5000
        })
    });

    // 发送请求响应
    const request = (c) => {
        let counter = 0;

        let i = setInterval(() => {
            if (counter >= 10) {
                // 清理定时器
                clearInterval(i);
                // 关闭连接
                c.disconnect();
            }

            // 发送消息
            try {
                c.request(1, buffer, 2000).then((message) => {
                    document.write('response message: ', (new TextDecoder).decode(message.buffer), '<br/>');
                }).catch(() => {
                    document.write('reject', '<br/>');
                });

                counter++;
            } catch (error) {
                console.log(error);
            }
        }, 1000);
    }

    // 发送异步消息
    const send = (c) => {
        let counter = 0;

        let i = setInterval(() => {
            if (counter >= 10) {
                // 清理定时器
                clearInterval(i);
                // 关闭连接
                c.disconnect();
            }

            // 发送消息
            try {
                c.send({
                    route: 1,
                    buffer: buffer
                });

                counter++;
            } catch (error) {
                console.log(error);
            }
        }, 1000);
    }

    // 监听连接
    client.onConnect((c) => {
        document.write('connect success', '<br/>');

        // 发送同步请求，需要客户端和服务器同时开启seq配置
        request(c);

        // 发送异步消息
        // send(c);
    });

    // 监听连接断开
    client.onDisconnect((c) => {
        document.write('disconnect success', '<br/>');

        // 重新连接
        c.connect();
    });

    // 监听接收到消息
    client.onReceive((c, message) => {
        document.write('receive message: ', (new TextDecoder).decode(message.buffer), '<br/>');
    });

    // 监听接受服务器的心跳附带的服务器时间
    client.onHeartbeat((c, millisecond) => {
        millisecond && document.write("server heartbeat timestamp: ", millisecond, '<br/>');
    });

    // 建立连接
    client.connect();
</script>

</html>